<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Category extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //接收数据
        $parent_id = input('get.parent_id', 0, 'intval');
        $category = model('Category')->getFirstCategorys($parent_id);
//        dump($category);
        return $this->fetch('', ['category' => $category]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        $category = model('category')->getNormalFirstCategory();
        return $this->fetch('', ['category' => $category]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //接收数据
        $data = input('post.');
//        $data['status'] = 100;
        //进行验证
        $validate = validate('Category');
        if (!$validate->scene('add')->check($data)) {
            $this->error($validate->getError());
        }
        model('Category')->add($data);
        $this->success('保存成功');
    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     * 分类编辑界面
     */
    public function edit($id = 0, Request $request)
    {
        if ($request->isGet()) {
            //显示数据
            if (intval($id) < 1) {
                $this->error('参数不合法');
            }
            $category = model('category')->getNormalFirstCategory();
            $name = model('category')->get($id);
            return $this->fetch('', ['category' => $category, 'name' => $name]);
        } else {
            //获取数据
            $category = input('post.');
            if (!empty($category['id'])) {
                $data = model('category')->update($category, ['id' => $category['id']]);
            }
            if (!$data) {
                $this->error('更新失败');
            } else {
                $this->success('更新成功');
            }
        }

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function listorder($id, $listorder)
    {
        $res = model('category')->save(['listorder' => $listorder], ['id' => $id]);
        if ($res) {
            $this->result($_SERVER['HTTP_REFERER'], 1, 'success');
        } else {
            $this->result($_SERVER['HTTP_REFERER'], 0, 'error');
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */

    public function getCategorySon($parent_id)
    {
        $category = model('category')->getFirstCategorys($parent_id);
        if ($category) {
            return show(1, 'success', $category);
        } else {
            return show(0, 'error');
        }

    }
}
